<template>
    <div class="main-wrap">
      <el-tabs type="card" closable :value="$route.path" @tab-remove="tabRemove" @tab-click="tabClick">
        <el-tab-pane v-for="tab in tabs" :name = "tab.name" :label="tab.label">
        </el-tab-pane>
      </el-tabs>
      <template v-if="isShow">
        <div class="main-space"></div>
        <div class="main-content">
          <router-view/>
        </div>

      </template>
    </div>
</template>
<script>
import _ from 'lodash'
    export default {
        name: 'App',
        computed:{
            tabs () {
              return this.$store.state.tabs;
            },
            isShow () {
              return this.$store.state.tabs.length >0;
            }
        },
        data () {
            return {
            }
        },
        methods:{
          tabRemove (name) {
            //判断删除的tab是否是当前选中的tab,如果是，则直接删除了即可。
            //如果不是则需要激活当前删除tab的下一个tab。
            let next = _.findIndex(this.$store.state.tabs,function (item) {
              return item.name == name;
            });
            let nextTab = this.$store.state.tabs[next + 1];
            this.$store.commit("removeTabs",name);
            if( this.$route.path == name) {
              //如果有一个元素，则定位到下一个元素，没有则定位到最后一个元素
              if (nextTab == undefined || nextTab == null) {
                let lastTab = _.last(this.$store.state.tabs);
                if (lastTab == undefined || lastTab == null) {

                } else {
                  this.$router.push(_.last(this.$store.state.tabs).name)
                }
              } else {
                this.$router.push(nextTab.name);
              }
            }
          },
          tabClick(tab) {
            this.$router.push(tab.name);
          }
        },
      mounted () {
        if (this.$route.path == "/") {
          this.$store.commit('addTabs',{name:"/home",label:'首页'});
          this.$router.push("/home");
        } else {
          this.$store.commit('addTabs',{name:this.$route.path,label:this.$route.name});
        }

      }
    }
</script>
<style>
.el-tabs--card>.el-tabs__header {
  margin: 0px;
}
.main-wrap {
  background-color: #fff;
}

.main-content {
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
}
.main-space {
  background-color: rgb(240, 242, 245);
  height: 10px;
}

</style>
